<?php

namespace app\admin\controller;

use app\comm\func\CommFunc;
use think\Controller;
use think\Db;
use think\Request;

/**
 * Class Admin 管理员模块
 * @package app\admin\controller
 */
class Admin extends Controller
{
    /**
     * @param Request $request 管理员列表
     * @return \think\response\View
     */
    public function adminList(Request $request)
    {
        $data['user'] = Db::table('admin a')
            ->join('admin_role ar', 'a.role_id=ar.role_id', 'left')
            ->order('a.aid')
            ->select();
        return view('', $data);
    }

    /**
     * @param Request $request 管理员添加
     */
    public function adminAdd(Request $request)
    {
        if ($request->isPost()) {
            $data = ['name', 'password', 'password2', 'phone', 'role_id'];
            CommFunc::emptyVerify($request->post(), $data);
            CommFunc::conditionAdd($condition, $request->request(), $data);

            $condition['password'] != $condition['password2'] ? CommFunc::ajaxReturn(['status' => 0, 'msg' => '密码不一致']) : true;

            Db::table('admin')
                ->where('name', $condition['name'])
                ->count() > 0 ? CommFunc::ajaxReturn(['status' => 0, 'msg' => '用户名重复']) : true;

            Db::table('admin')
                ->where('phone', $condition['phone'])
                ->count() > 0 ? CommFunc::ajaxReturn(['status' => 0, 'msg' => '手机号重复']) : true;

            $condition['name'] = trim($condition['name']);
            $condition['password'] = md5(trim($condition['password']));
            unset($condition['password2']);
            $condition['phone'] = trim($condition['phone']);

            Db::table('admin')->insert($condition) > 0
                ? CommFunc::ajaxReturn(['status' => 1, 'msg' => '添加成功']) : CommFunc::ajaxReturn(['status' => 0, 'msg' => '添加失败']);

        } else {
            $data['roles'] = Db::table('admin_role')->select();
            return view('', $data);
        }
    }

    /**
     * @param Request $request 管理员修改
     */
    public function adminEdit(Request $request)
    {
        if ($request->isPost()) {
            $data = ['name', 'password', 'password2', 'phone', 'role_id', 'aid'];
            CommFunc::emptyVerify($request->post(), $data);
            CommFunc::conditionAdd($condition, $request->post(), $data);

            $res['name'] = trim($condition['name']);
            $res['password'] = md5(trim($condition['password']));
            $res['phone'] = trim($condition['phone']);
            $res['role_id'] = $condition['role_id'];

            Db::table('admin')->where('name', $res['name'])->where('aid', '<>', $condition['aid'])->count() > 0
                ? CommFunc::ajaxReturn(['status' => 0, 'msg' => '该管理员已存在']) : true;

            Db::table('admin')->where('aid', $condition['aid'])->update($res) > 0
                ? CommFunc::ajaxReturn(['status' => 1, 'msg' => '修改成功']) : CommFunc::ajaxReturn(['status' => 0, 'msg' => '修改失败']);
        } else {
            CommFunc::emptyVerify($request->get(), ['aid']);
            CommFunc::conditionAdd($condition, $request->get(), ['aid']);

            $res = Db::table('admin')->where('aid', $condition['aid'])->find();

            $res['role_id'] == 1
                ? $data['roles'] = Db::table('admin_role')->field('role_desc', true)->select()
                : $data['roles'] = Db::table('admin_role')->field('role_desc', true)->where('role_id', '<>', 1)->select();
            $data['admin'] = Db::table('admin')->where('aid', $condition['aid'])->find();
            return view('', $data);
        }
    }

    /**
     * @param Request $request 管理员删除
     */
    public function adminDel(Request $request)
    {
        CommFunc::emptyVerify($request->post(), ['id']);
        CommFunc::conditionAdd($condition, $request->post(), ['id']);

        Db::table('admin')->where('aid', $condition['id'])->delete() > 0
            ? CommFunc::ajaxReturn(['status' => 1, 'msg' => '删除成功']) : CommFunc::ajaxReturn(['status' => 0, 'msg' => '删除失败']);
    }

    /**
     * @param Request $request 启用停用
     */
    public function Lock(Request $request)
    {
        CommFunc::emptyVerify($request->post(), ['id']);
        CommFunc::conditionAdd($condition, $request->post(), ['id']);

        $result = Db::table('admin')->where('aid', $condition['id'])->find();

        $result['is_type'] == 1 ? $data['is_type'] = 2 : $data['is_type'] = 1;

        Db::table('admin')->where('aid', $condition['id'])->update($data) > 0
            ? CommFunc::ajaxReturn(['status' => 1, 'msg' => '修改成功']) : CommFunc::ajaxReturn(['status' => 0, 'msg' => '修改失败']);
    }

    /**
     * @param Request $request 权限列表
     */
    public function adminPermission(Request $request)
    {
        $list = Db::table('access')->select();
        $datas = [];
        foreach ($list as $key => $vo) {
            if ($vo['parent_id'] == 0) {
                $datas[] = $vo;
                foreach ($list as $k => $v) {
                    if ($v['parent_id'] == $vo['access_id']) {
                        $datas[] = $v;
                    }
                }
            }
        }
        $datas = empty($datas) ? $list : $datas;
        $data['datas'] = $datas;
        $data['heng'] = '-';
        return view('', $data);
    }

    /**
     * @param Request $request 增加权限
     * 权限无法删除和修改
     */
    public function adminPermissionAdd(Request $request)
    {
        if ($request->isPost()) {
            $data = ['title', 'controller', 'action', 'parent_id', 'orderby', 'icon'];
            CommFunc::emptyVerify($request->post(), $data);
            CommFunc::conditionAdd($condition, $request->post(), $data);
            if ($condition['parent_id'] == 0) {
                Db::table('access')->where('title', $condition['title'])->where('parent_id', 0)->count() > 0
                    ? CommFunc::ajaxReturn(['status' => 0, 'msg' => '一级菜单已经存在']) : true;
                $condition['module'] = 'menu';
                $condition['level'] = 1;
            } else {
                $condition['module'] = 'module';
                $condition['level'] = 2;
            }
            Db::table('access')->insert($condition) > 0
                ? CommFunc::ajaxReturn(['status' => 1, 'msg' => '添加成功']) : CommFunc::ajaxReturn(['status' => 0, 'msg' => '添加失败']);
        } else {
            $list = Db::table('access')->where('module', 'menu')->select();
            $this->assign('list', $list);
            return view();
        }
    }

    /**
     * @param Request $request 角色列表
     */
    public function roleList(Request $request)
    {
        $arr = Db::name('admin_role')->select();
        $this->assign('role', $arr);
        return view();
    }

    /**
     * @param Request $request 角色添加
     * @return \think\response\View
     */
    public function roleAdd(Request $request)
    {
        if ($request->isPost()) {
            $role = [];
            $data = $request->post();
            $role['role_name'] = $data['role_name'];
            $role['role_desc'] = $data['role_desc'];
            Db::startTrans();
            $id = Db::table('admin_role')->insertGetId($role);
            if ($id > 0) {
                if (!empty($data['access'])) {
                    foreach ($data['access'] as $vo) {
                        $new = [];
                        $new['role_id'] = $id;
                        $new['access_id'] = $vo;
                        if (Db::table('role_access')->insert($new) > 0) {
                            continue;
                        } else {
                            Db::rollback();
                            CommFunc::ajaxReturn(['status' => 0, 'msg' => '添加失败']);
                        }
                    }
                    Db::commit();
                    CommFunc::ajaxReturn(['status' => 1, 'msg' => '添加成功']);
                }
            } else {
                Db::rollback();
                CommFunc::ajaxReturn(['status' => 0, 'msg' => '添加失败']);
            }
        } else {
            $this->assign('menus', $this->getmenu());
            return view();
        }
    }

    /**
     * @param Request $request 角色修改
     */
    public function roleEdit(Request $request)
    {
        if ($request->isPost()) {
            $data['role_name'] = $request->post('role_name');
            $data['role_desc'] = $request->post('role_desc');
            $role_id = $request->post('role_id');
            if (Db::name('admin_role')->where('role_name', $data['role_name'])->where('role_id', '<>', $role_id)->count() > 0) {
                CommFunc::ajaxReturn(['status' => 0, 'msg' => '角色名重复']);
            }
            $access = $request->post('access/a');
            Db::startTrans();
            Db::name('admin_role')->where('role_id', $role_id)->update($data);
            Db::name('role_access')->where('role_id', $role_id)->delete();
            if (!empty($access)) {
                foreach ($access as $key => $value) {
                    $new = [];
                    $new['role_id'] = $role_id;
                    $new['access_id'] = $value;
                    if (Db::name('role_access')->insert($new) > 0) {
                        continue;
                    } else {
                        Db::rollback();
                        CommFunc::ajaxReturn(['status' => 0, 'msg' => '修改失败']);
                    }
                }
            }
            CommFunc::ajaxReturn(['status' => 1, 'msg' => '修改成功']);
        } else {
            $data['access'] = $this->getmenu();
            $data['role'] = Db::name('admin_role')->where('role_id', $request->get('id'))->find();
            $data['access_id'] = Db::name('role_access')->where('role_id', $request->get('id'))->column('access_id');
            return view('', $data);

        }
    }

    /**
     * @param Request $request 角色删除
     */
    public function roleDel(Request $request)
    {
        $role_id = $request->get('role_id');
        if (Db::name('admin')->where('role_id', $role_id)->count() > 0) {
            CommFunc::ajaxReturn(['status' => 0, 'msg' => '无法删除']);
        }
        Db::startTrans();
        try {
            $res1 = Db::name('admin_role')->delete($role_id);
            $res2 = Db::name('role_access')->where('role_id', $role_id)->delete();
            Db::commit();
            CommFunc::ajaxReturn(['status' => 1, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            Db::rollback();
            CommFunc::ajaxReturn(['status' => 1, 'msg' => '删除失败']);
        }
    }

    /**
     * @return array 获取菜单
     */
    public function getmenu()
    {
        $datas = Db::table('access')->where('parent_id', 0)->select();
        foreach ($datas as &$vo) {
            $list = Db::name('access')->where('parent_id', $vo['access_id'])->select();
            if (!empty($list)) {
                $vo['childnodes'] = $list;
            }
        }
        return array($datas);
    }
}